<template>
  <!-- 1.display: flex;使用弹性布局，让父元素中的子元素横置，且父元素会根据子元素浮动后的实际高度自动填充高度   -->
  <div style="display: flex;">
    <!--2.isCollapse为true:折叠左侧菜单栏,左侧菜单栏宽度为64px,右侧主体宽度为calc(100% - 64px)-->
    <div :style="{width:( isCollapse ? '64px': '208px')}">
      <!--4.左侧菜单栏-->
      <!-- unique-opened只允许同时打开一项菜单项 router允许菜单项进行路由跳转 -->
      <el-menu
          background-color="#c4e2fb"
          style="width:100%;height:100vh;"
          text-color="#555555"
          active-text-color="#ff0"
          :collapse="isCollapse"
          :collapse-transition="false"
          unique-opened router
      >
        <!--4.1 左侧菜单栏的顶部条 注意:顶部条也要写在el-menu里！-->
        <el-row style="padding-top: 10px;">
          <el-col :span="2">
          </el-col>
          <el-col :span="7" style="padding-left:7px;">
            <el-avatar src="/imgs/admin/logo.png"
                       style="width:35px;height:35px;"></el-avatar>
          </el-col>
          <el-col :span="isCollapse ? 0 : 13">
                        <span
                            style="color:#555555;position:relative;top:8px;left:2px;font-weight: bold;">
                            安心陪诊
                        </span>
          </el-col>
        </el-row>
        <!--4.2 左侧菜单栏的导航项 -->
         <el-sub-menu index="1">
        <template #title>
          <el-icon style="font-size:21px;"><User/></el-icon><span>个人中心</span>
        </template>
        <el-menu-item index="/managerPersonal">个人中心</el-menu-item>
      </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>
            <el-icon style="font-size:21px;"><User/></el-icon><span>用户管理</span>
          </template>
          <el-menu-item index="/user">用户列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="3">
          <template #title>
            <el-icon style="font-size:21px;"><UserFilled/></el-icon>
            <span>陪诊员管理</span>
          </template>
          <el-menu-item index="/escort">陪诊员列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="4">
          <template #title>
            <el-icon style="font-size:21px;"><Platform/></el-icon>
            <span>陪诊服务管理</span>
          </template>
          <el-menu-item index="/service">陪诊服务列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="5">
          <template #title>
            <el-icon style="font-size:21px;"><Calendar/></el-icon>
            <span>陪诊预约管理</span>
          </template>
          <el-menu-item index="/appointment">陪诊预约列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="6">
          <template #title>
            <el-icon style="font-size:21px;"><Checked /></el-icon>
            <span>陪诊员审核</span>
          </template>
          <el-menu-item index="/escortAudit">审核列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="7">
          <template #title>
            <el-icon style="font-size:21px;"><ChatLineRound/></el-icon>
            <span>服务评价管理</span>
          </template>
          <el-menu-item index="/review">评价列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="8">
          <template #title>
            <el-icon style="font-size:21px;"><Coordinate /></el-icon>
            <span>服务跟踪管理</span>
          </template>
          <el-menu-item index="/serviceTrack">服务跟踪列表</el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="9">
          <template #title>
            <el-icon style="font-size:21px;"><Tickets /></el-icon>
            <span>公告管理</span>
          </template>
          <el-menu-item index="/noticeManager">公告列表</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
    <!--3.isCollapse为false:不折叠左侧菜单栏,左侧菜单栏宽度为208px,右侧主体宽度为calc(100% - 208px)-->
    <div :style="{width:( isCollapse ? 'calc(100% - 64px)': 'calc(100% - 208px)')}">
      <!--5.右侧:顶部菜单栏-->
      <!--5.右侧:顶部菜单栏-->
      <el-header style="padding-top:22px;height:10vh;background-color:#fff;">
        <!--5.1 折叠图标与退出登录-->
        <el-row :gutter="10">
          <el-col :span="18">
            <el-icon style="font-size:20px;" @click="changeCollapsed"><Expand/></el-icon>
          </el-col>
          <el-col :span="6" style="position: relative;">
            <el-dropdown trigger="click" style="position:absolute;right:20px;">
                     <span style="font-size:19px;font-weight: bold;">
                         {{ managerInfo.username || 'manager'}}
                         <el-icon><arrow-down/></el-icon>
                     </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
        <!-- 面包屑导航  -->
        <el-breadcrumb separator="/" style="position: relative;top: 20px;">
          <el-breadcrumb-item v-for="item in breadcrumb">{{item}}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>
      <!-- 右侧主体内容(可变区域) -->
      <el-main style="height:90vh;padding: 0;overflow-y: auto;">
        <router-view/>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
// import {useRouter} from "vue-router";
import { useRoute, useRouter } from "vue-router";
import {ElMessage} from "element-plus";


//定义变量控制菜单是否折叠
const isCollapse = ref(false);
//修改折叠状态
const changeCollapsed = () => {
  isCollapse.value = !isCollapse.value;
}
//获取登录的用户信息
const manager = ref(getUser());

const managerInfo = ref({
  id: "",
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: "",
  createTime: ""
});

const managerForm = ref({
  id: "",
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: ""
});

const loading = ref(true);

// 获取管理员信息
// 在 script setup 部分修改 fetchManagerInfo 函数
const fetchManagerInfo = async () => {
  try {
    loading.value = true;

    // 首先尝试从 localStorage 读取管理员信息
    const storedManager = localStorage.getItem('managerInfo');
    if (storedManager) {
      const parsedManager = JSON.parse(storedManager);
      console.log(parsedManager);
      managerInfo.value = parsedManager;
      managerForm.value = {
        id: parsedManager.id,
        username: parsedManager.username,
        password: "********", // 密码不存储明文
        realName: parsedManager.realName,
        phone: parsedManager.phone,
        email: parsedManager.email
      };
      console.log(managerInfo.value);
    }

    // 无论是否有本地存储，都请求最新数据
    const response = await axios.post(BASE_URL + '/v1/manager/personal', {}, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
      }
    });

    if (response.data.state === 2000) {
      const newManagerInfo = {
        id: response.data.data.id || "",
        username: response.data.data.username || "",
        password: response.data.data.password || "",
        realName: response.data.data.realName || "",
        phone: response.data.data.phone || "",
        email: response.data.data.email || "",
        createTime: response.data.data.createTime || ""
      };

      // 更新本地存储
      localStorage.setItem('managerInfo', JSON.stringify(newManagerInfo));

      // 更新界面数据
      managerInfo.value = newManagerInfo;
      managerForm.value = {
        id: newManagerInfo.id,
        username: newManagerInfo.username,
        password: "********",
        realName: newManagerInfo.realName,
        phone: newManagerInfo.phone,
        email: newManagerInfo.email
      };
    } else {
      ElMessage.error(response.data.message || "获取管理员信息失败");
    }
  } catch (error) {
    console.error("获取管理员信息出错:", error);
    // 如果API请求失败但本地有数据，可以继续使用本地数据
    if (!localStorage.getItem('managerInfo')) {
      ElMessage.error(error.response?.data?.message || "获取管理员信息失败");
    }
  } finally {
    loading.value = false;
  }
};

//退出登录功能
const logout = ()=>{
  if(confirm('您确认要退出登录吗?')){
    //退出时要清空用户数据
    localStorage.removeItem('manager');
    //退出后要去到登录页
    window.location.href = '/login';
    //也需要把已经取出来的user对象清空
    manager.value = '';
  }
}

//定义数组用来保存当前展示的面包屑导航的值
const breadcrumb = ref([]);
//定义对象用来维护路由path与面包屑值的对应关系
let map = {
  '/managerPersonal':['个人中心','个人信息'],
  '/user':['用户管理','用户列表'],
  '/escort':['陪诊员管理','陪诊员列表'],
  '/service':['陪诊服务管理','陪诊服务列表'],
  '/appointment':['陪诊预约管理','陪诊预约列表'],
  '/escortAudit':['陪诊员审核','审核列表'],
  '/review':['服务评价管理','评价列表'],
  '/serviceTrack':['服务跟踪管理','服务跟踪列表'],
  '/noticeManager':['公告管理','公告列表']
};
//一进入页面立即加载的函数,只有第一次进入页面才会触发(刷新页面)
onMounted(()=>{
  fetchManagerInfo();
  updateBreadcrumb(route);
})
//useRoute()是vue路由器提供的一个方法,用来访问当前组件的路由状态,获取的就是当前路由对象
const route = useRoute();
//定义更新面包屑导航值的方法
const updateBreadcrumb = (route)=> {
  //从当前路由对象中获取到当前的path
  const path = route.path;
  breadcrumb.value = map[path];
}
//获取路由守卫,监听路由,只要path发生了改变(包括点左侧菜单栏),就立即更新面包屑的值,再进行跳转
const router = useRouter();
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})
</script>